package com.liu.sx.service;

import com.liu.sx.common.entity.Result;
import com.liu.sx.common.status.CodeEnum;
import com.liu.sx.common.util.ChannelHolder;
import com.liu.sx.common.util.IdWorker;
import com.liu.sx.dao.TaskDao;
import com.liu.sx.entity.Task;
import com.liu.sx.handler.ServerHanlderUp;
import com.liu.sx.netty.Client;
import com.liu.sx.pojo.BW;
import com.liu.sx.util.BwUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
@Transactional
public class TaskService {

    @Autowired
    private TaskDao taskDao;

    @Autowired
    private IdWorker idWorker;

    public String doIpAndPort(Task task) {
        System.out.println("====TaskService=======");

        System.out.println(task);

       Map<String ,Channel> map =ChannelHolder.getAllClient();
        System.out.println(map.toString());
      Channel ctx =map.get(task.getAddress());




        if(ctx == null){
            addTask(task);
            return "消息存入队列，上线后发送";
        }
        Client client = new Client(ctx);
       BW bw = BwUtil.task2BW(task);
        System.out.println(bw);
        boolean flag =client.sendMsg(bw);
        if (!flag){
            addTask(task);
            return  "设备离线,任务将添加到任务列表中";
        }else {


            return "消息发送成功！！";
        }

    }

    public void addTask(Task task){
        task.setId(idWorker.nextId()+"");
        taskDao.save(task);
    }

    public List<Task> findAllTask() {
        return taskDao.findAll();
    }

    public Page<Task> findPageTask(int num, int rows, String query) {
        if(num==0){
            num=1;
        }
        Pageable pageable = PageRequest.of(num-1,rows, Sort.Direction.DESC,"createTime");
        return  taskDao.findAll(query,pageable);
    }
}
